package cn.edu.csust.coursecard.websocket;

import cn.edu.csust.coursecard.common.CodeEnum;
import cn.edu.csust.coursecard.dao.dto.TaskResult;
import cn.edu.csust.coursecard.exception.BaseException;
import cn.edu.csust.coursecard.utils.ApplicationContextProvider;
import cn.edu.csust.coursecard.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/cluster/{nodeId}")  // 接口路径 ws://localhost:8087/webSocket/userId;
public class WebSocket {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocket.class);

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private static final ConcurrentHashMap<String, WebSocket> clusterWebSockets = new ConcurrentHashMap<>();

    public static final List<String> nodeIds = new ArrayList<>();

    private static RedisUtil redisUtil;

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "nodeId") String nodeId) {
        if (redisUtil == null) {
            redisUtil = ApplicationContextProvider.getBean(RedisUtil.class);
        }
        try {
            this.session = session;
            clusterWebSockets.put(nodeId, this);
            nodeIds.add(nodeId);
            LOGGER.info("[WebSocket]有新的连接，总数为:" + getConnCount());
        } catch (Exception e) {
            throw new BaseException(CodeEnum.SYSTEM_ERROR.getCode(), "[WebSocket]OnOpen异常:" + e.getMessage());
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("nodeId") String nodeId) {
        try {
            clusterWebSockets.remove(nodeId);
            nodeIds.remove(nodeId);
            LOGGER.info("[WebSocket]连接断开，总数为:" + getConnCount());
        } catch (Exception e) {
            throw new BaseException(CodeEnum.SYSTEM_ERROR.getCode(), "[WebSocket]OnClose异常:" + e.getMessage());
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message, @PathParam("nodeId") String nodeId) {
        WebSocket ws = clusterWebSockets.get(nodeId);
        Session session = ws.session;
        LOGGER.debug("[WebSocket]接收子节点消息:" + message);
        LOGGER.info("[WebSocket]接收子节点消息");
        try {
            TaskResult response = new ObjectMapper().readValue(message, TaskResult.class);
            putTaskMessage(response.getTaskId(), message);
        } catch (Exception e) {
            onError(session, e);
        }
    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        LOGGER.error("[WebSocket]用户错误: " + error.getMessage());
    }

    // 发送消息（单点）
    public void sendMessage(String nodeId, String message) {
        WebSocket ws = clusterWebSockets.get(nodeId);
        Session session = ws.session;
        if (session != null && session.isOpen()) {
            try {
                LOGGER.info("[WebSocket]单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 发送消息(多人)
    public void sendMessage(String[] nodeIds, String message) {
        for (String nodeId : nodeIds) {
            sendMessage(nodeId, message);
        }
    }


    /**
     * 发送消息（顺序决定发送对象）
     *
     * @param clientNum 客户端数量
     * @param message   消息
     */
    public void sendMessage(int clientNum, String message) {
        String nodeId = nodeIds.get(clientNum);
        sendMessage(nodeId, message);
    }

    public void putTaskMessage(String taskId, String message) {
        redisUtil.set("ws::message::" + taskId, message, 3000L);
    }

    public int getConnCount() {
        return clusterWebSockets.size();
    }

    public String getTaskMessage(String taskId) {
        return (String) redisUtil.get("ws::message::" + taskId);
    }

}
